<!--上传-->
<template>
  <el-upload
    ref="refUploadImg"
    name="Picture"
    :action="uploadFile"
    list-type="picture-card"
    :class="{ disabled: uploadDisabled }"
    :auto-upload="false"
    :limit="1"
    :on-change="uploadImg"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
  >
    <div v-if="uploadLoad" v-loading="true" class="upload-loading" />
    <i class="el-icon-plus"></i>
    <div slot="tip" class="el-upload__tip">
      请上传大小在5M以内,格式为jpg、jpeg、png的图片,其他格式暂不支持
    </div>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </el-upload>
</template>
<script>
import { uploadFile, uploadImgFile } from "@/api/Base";
import { getToken } from "@/utils/auth";
import { formdataify } from "@/utils/index";
import { GetStaticImgInfo } from "@/api/Base";
export default {
  name: "BaseUpload",
  props: {
    value: {
      type: String,
      default: "",
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 文件类型
    accept: {
      type: String,
      default: ".png,.jpeg,.jpg",
    },
    // 文件大小
    fileSize: {
      type: Number,
      default: 500,
    },
    // 禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 业务类型,请在后端代码Panna.ModuleSystem.Api中的BusinessType中查找对应的业务枚举值
    businessType: {
      type: String,
      default: "0",
    },
    imageWidth: {
      type: String,
      default: "0",
    },
    imageHeight: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      filePath: "",
      fileList: [],
      uploadFile,
      uploadLoad: false,
      dialogVisible: false,
      dialogImageUrl: "",
      headers: { Authorization: getToken() },
    };
  },
  computed: {
    uploadDisabled: function() {
      return this.filePath !== "";
    },
  },
  watch: {
    value: function() {
      this.fileList = [];
      if (this.value) {
        this.filePath = this.value;
        this.dialogImageUrl = this.value;
        GetStaticImgInfo(this.value).then((res) => {
          this.fileList.push({
            name: "1",
            url: res.data,
          });
        });
      }
    },
    filePath: {
      handler(newName) {
        var aa = document.querySelector(".el-upload--picture-card");
        if (newName) {
          aa.style.display = "none";
        } else {
          setTimeout(() => {
            aa.style.display = "inline-block";
          }, 1100);
        }
      },
    },
  },
  methods: {
    // 上传完成
    uploadImg(info) {
      if (info.status === "ready") this.uploadLoad = true;
      if (!this.beforeUpload(info)) {
        this.$refs.refUploadImg.uploadFiles.splice(
          this.$refs.refUploadImg.uploadFiles.length - 1,
          1
        );
        return;
      }
      const obj = {
        businessType: this.businessType,
        imageWidth: this.imageWidth,
        imageHeight: this.imageHeight,
        file: info.raw,
      };
      const form = formdataify(obj);
      uploadImgFile(form)
        .then((res) => {
          this.uploadLoad = false;
          this.filePath = res.data.filePath;
          // this.$emit(
          //   "input",
          //   `${this.$baseProtocol}//${res.data.fileDomain}/${res.data.fileBucket}/${res.data.filePath}`
          // );
          this.$emit("input", `${res.data.filePath}`);
        })
        .catch(() => {
          console.log("uploadImgFile异常");
          this.uploadLoad = false;
        });

      if (info.status === "fail") {
        this.uploadLoad = false;
        this.$message.error("上传失败");
      }
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      const fileTypes = this.accept.split(",");
      var testmsg = file.name.substring(file.name.lastIndexOf("."));
      const checkFormat = fileTypes.includes(testmsg);
      if (!checkFormat) {
        this.$message.error(`请选择${this.accept}格式`);
      }
      const checkSize = file.size / 1024 <= this.fileSize;
      if (!checkSize) {
        this.$message.error(`图片必须小于${this.fileSize}KB！`);
      }
      this.uploadLoad = false;
      return checkFormat && checkSize;
    },
    handleRemove() {
      this.value = "";
      this.filePath = "";
      this.fileList = [];
      this.$emit("input", "");
    },
    // 图片预览
    handlePreview(file, files) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.disabled {
  .el-upload--picture-card {
    display: none;
  }
}

.base-upload {
  height: 136px;
  position: relative;

  .upload-button {
    width: 148px;
    height: 148px;
    background: #f7f8f9;
    border-radius: 4px;
    border: 1px #dedede dashed;

    img {
      display: block;
      width: 32px;
      height: auto;
      margin: 22px auto 10px;
    }

    span {
      display: block;
      width: 100%;
      font-size: 12px;
      line-height: 12px;
      font-weight: 500;
      color: #bfbfbf;
      transform: scale(0.8);
    }
  }

  .upload-cover {
    display: block;
    width: 148px;
    height: 148px;
    border-radius: 4px;
    object-fit: contain;
    border: 1px solid #dcdfe6;
  }

  .tip-text {
    position: absolute;
    margin-left: -6px;
    left: 0;
    bottom: -10px;
    display: block;
    width: 100%;
    word-break: break-word;
    text-align: left;
    font-size: 6px;
    color: #666666;
    line-height: 18px;
    transform: scale(0.9);
  }

  .upload-loading {
    position: absolute;
    left: 0;
    top: 0;
    width: 148px;
    height: 148px;
    background-color: rgba(255, 255, 255, 0.8);
    z-index: 10;
    padding: 1px;
    box-sizing: border-box;
  }

  .no-upload {
    cursor: no-drop;
  }
}
</style>
